<?php

namespace Iwester\Http\Controllers\Admin\Book;

use Illuminate\Support\Facades\Auth;
use Iwester\Http\Controllers\Admin\BaseController;
use App\Console\Commands\SiteMap;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Http\Model\Article\Article;
use Iwester\Http\Model\Article\ArticleComment;
use Iwester\Http\Model\Article\ArticleCommentLike;
use Iwester\Http\Model\Article\ArticleContent;
use Iwester\Http\Model\Article\ArticleLike;
use Iwester\Http\Model\Article\ArticleTag;
use Iwester\Http\Model\Book\BookAuthor;
use Iwester\Http\Model\Book\BookCategory;
use Iwester\Http\Model\Config\SiteConfig;
use Iwester\Http\Requests\Book\BookCategoryRequest;
use Monolog\Handler\IFTTTHandler;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;


class AdminBookAuthorController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * 书籍 - 作者管理
     * @return Response
     */
    public function author(Request $request)
    {
        $search = $request->get('search', false);
        $query = BookAuthor::where('status', BookAuthor::CAN_USE);
        if($search) $query->where('author_name', 'like', '%'.$search.'%');
        $authors = $query->paginate(20);
        return view('iwester::admin.book.author.author', [
            'authors'=> $authors,
            'params' => $request->all()
        ]);
    }

    /**
     * 编辑作者
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        $bookAuthor = BookAuthor::find($id);
        return view('iwester::admin.book.author.edit', [
            'bookAuthor'=> $bookAuthor
        ]);
    }

    /**
     * 编辑保存作者
     * @param Request $request
     */
    public function store(Request $request)
    {
        try {
            \DB::beginTransaction();
            $id = $request->input('id', false);
            $param = $request->get('author', []);
            if ($id) {
                $bookAuthor = BookAuthor::find($id);
                $bookAuthor->update($param);
            } else {
                $bookAuthor = BookAuthor::create($param);
            }
            \DB::commit();
            return redirect(route('book.author'));
        } catch (\Exception $e) {
            \DB::rollBack();
            return redirect()->route('book.author')->with('errors', ['系统错误，保存失败']);
        }
    }

}
